﻿using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using XF.Common;
using XF.Common.WeChat;
using XF.Meeting.DAL;
using XF.Meeting.Entity.dbEntity;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Query;

namespace EWS
{
    public class ExchangeToDbService
    {

        public ExchangeToDbDal dal = null;
        public ExchangeToDbService(string Operator, string OperaIP)
        {
            this.Operator = Operator;
            this.OperaIP = OperaIP;
            if (dal == null)
            {
                lock (this.OperaIP)
                {
                    if (dal == null)
                    {
                        dal = new ExchangeToDbDal();
                    }
                }
            }
        }
        /// <summary>
        /// 插入会议信息
        /// </summary>
        /// <param name="itemId">ews itemiD</param>
        /// <param name="emailAdress">创建人邮箱</param>
        public Task<bool> insert(ExchangeQuery query, string mail)
        {
            try
            {
                double time = (query.start - DateTime.Now).TotalMinutes;
                bool isTen = false;
                var email = ExChangeHelper.GetEmailListByItemID(query).Result;
                EmailEntity meet = getEmailEntity(email);
                var list = new List<EmailEntity>();
                meet.SourceType = 0;
                isTen = time > 10 ? false : true;
                var (result, id) = dal.Insert(meet, out string ss).Result;
                //if (result)
                //{
                //    var wx = new WeChatHelper();
                //    wx.SendWxMssage(new CRoomPadQuery()
                //    {
                //        CInfoId = id,
                //        type = 1

                //    }, isTen);

                //}
                return System.Threading.Tasks.Task.FromResult(result);
            }
            catch (Exception)
            {

                return System.Threading.Tasks.Task.FromResult(false);
            }

        }
        public Task<bool> insertZhouqi(Appointment appointment)
        {
            try
            {
                //  var query = new ExchangeQuery(appointment.ICalUid, appointment.Organizer.Address, appointment.Start, appointment.End);
                // double time = (query.start - DateTime.Now).TotalMinutes;
                bool isTen = false;

                var list = new List<ZhouqiEntity>();
                var master = new Appointment(appointment.Service);
                if (appointment.AppointmentType == AppointmentType.RecurringMaster)
                {
                    master = appointment;
                }
                else if (appointment.AppointmentType == AppointmentType.Occurrence || appointment.AppointmentType == AppointmentType.Exception)
                {
                    master = Appointment.BindToRecurringMaster(appointment.Service, appointment.Id);
                }
                list = GetZhouqiItemList(master);

                bool result = false;
                int id = 0;
                int idd = 0;
                //  isTen = time > 10 ? false : true;
                foreach (var item1 in list)
                {
                    var item = item1.EmailEntity;
                    if (item1.IsDelete)
                    {
                        item.state = 5;
                        continue;
                    }


                    if (item.Start < DateTime.Now && item.End < DateTime.Now)
                    {
                        item.state = 3;
                    }
                    //已预定
                    else if (item.Start > DateTime.Now && item.End > DateTime.Now)
                    {
                        item.state = 1;
                    }
                    //进行中
                    else if (item.Start <= DateTime.Now && item.End >= DateTime.Now)
                    {
                        item.state = 2;
                    }
                    // item.itemId = item.MasterId;
                    (result, id) = dal.Insert(item, out string ss).Result;
                    Task<bool> b = dal.InsertZhouQiTemp(item, out ss);
                    if (idd == 0)
                    {
                        idd = id;
                    }
                }

                //if (result)
                //{
                //    var wx = new WeChatHelper();
                //    wx.SendWxMssage(new CRoomPadQuery()
                //    {
                //        CInfoId = idd,
                //        type = 3

                //    }, isTen);

                //}
                return System.Threading.Tasks.Task.FromResult(result);
            }
            catch (Exception e)
            {
                return System.Threading.Tasks.Task.FromResult(false);

            }
        }

        private List<ZhouqiEntity> GetZhouqiItemList(Appointment master)
        {
            List<ZhouqiEntity> list = new List<ZhouqiEntity>();
            var email = master;
            Appointment maill = null;
            var userAddress = "";
            if (email.Organizer != null)
            {
                maill = GetEmailListByItemID(new ExchangeQuery(email.ICalUid, email.Organizer.Address, email.Start.AddDays(-1), email.End.AddDays(1))).Result;
            }
            else
            {
                userAddress = "product.team@3dmedcare.com";
                maill = GetEmailListByItemID(new ExchangeQuery(email.ICalUid, userAddress, email.Start.AddDays(-1), email.End.AddDays(1))).Result;
            }


            var userMaster = Appointment.BindToRecurringMaster(maill.Service, maill.Id, new PropertySet());
            EmailEntity meet = getEmailEntity(maill, userAddress);
            meet.IsRecurring = true;
            meet.SourceType = 3;
            var RecurrenceType = master.Recurrence;
            PropertySet properties = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.ICalUid);
            switch (RecurrenceType)
            {
                case Recurrence.DailyPattern _:
                    list = getDaily(meet, userMaster, RecurrenceType as Recurrence.DailyPattern, properties).Result;
                    break;
                case Recurrence.WeeklyPattern _:
                    list = getWeekly(meet, userMaster, RecurrenceType as Recurrence.WeeklyPattern, properties);
                    break;
                case Recurrence.MonthlyPattern _:
                    list = getMonthly(meet, userMaster, RecurrenceType as Recurrence.MonthlyPattern, properties);
                    break;
                case Recurrence.YearlyPattern _:
                    list = getYearly(meet, userMaster, RecurrenceType as Recurrence.YearlyPattern, properties);
                    break;
            }

            return list;
        }

        public static async Task<Appointment> GetEmailListByItemID(ExchangeQuery query)
        {

            try
            {

                var serv = ExChangeHelper.getExChangeHelper(query.address);
                //初始化会议对象
                //Appointment oAppt = Appointment.Bind(serv, ItemId, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End,AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid));
                var view = new CalendarView(query.start, query.end);
                view.PropertySet = new PropertySet();
                //var userMeet = UserService.FindAppointments(WellKnownFolderName.Calendar,view);
                CalendarFolder calendar = CalendarFolder.Bind(serv, WellKnownFolderName.Calendar, new PropertySet());
                // Set the start and end time and number of appointments to retrieve.

                // Limit the properties returned to the appointment's subject, start time, and end time.

                FindItemsResults<Appointment> appointments = calendar.FindAppointments(view);
                var id = appointments.Where(i => i.ICalUid == query.Icaluid).FirstOrDefault();

                Appointment oApt = Appointment.Bind(serv, id.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.Id, AppointmentSchema.ICalUid, AppointmentSchema.AppointmentType));
                return oApt;
            }
            catch (Exception ex)
            {
                CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}dateme:{DateTime.Now}");
                var fail = true;
                var count = 1;
                Appointment meet = null;
                while (fail)
                {
                    if (count > 4)
                    {
                        CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid}dateme:{DateTime.Now}-已经20秒过去~");
                        break;
                    }
                    meet = await ExChangeHelper.GetMeetByItemID(query);
                    if (meet != null)
                    {
                        fail = false;

                        CLogger.Info($"{ex.Message}::::未查询到用户：{query.address},开始时间：{query.start};结束时间：{query.end},id:{query.Icaluid} datetime:{DateTime.Now}");
                    }
                    else
                    {


                    }
                    count++;
                }
                return meet;
            }

        }
        public Task<bool> Update(ExchangeQuery query)
        {
            var email = ExChangeHelper.GetEmailListByItemID(query).Result;
            EmailEntity meet = getEmailEntity(email);
            bool check = dal.CheckIsCreated(meet);
            if (check)
            {
                return dal.Update(meet, out string ss);
            }
            else
            {
                meet.SourceType = 2;
                var (result, id) = dal.Insert(meet, out string ss).Result;
                double time = (query.start - DateTime.Now).TotalMinutes;
                bool isTen = false;
                isTen = time > 10 ? false : true;
                //if (result)
                //{
                //    var wx = new WeChatHelper();
                //    wx.SendWxMssage(new CRoomPadQuery()
                //    {
                //        CInfoId = id,
                //        type = 1

                //    }, isTen);
                //}
                return System.Threading.Tasks.Task.FromResult(result);
            }

        }
        public void updateZhouqi(Appointment oAppt)
        {

            Appointment recurringMaster = null;
            if (oAppt.AppointmentType != AppointmentType.RecurringMaster)
            {
                // If an occurrence was passed in, bind to the master.
                try
                {
                    recurringMaster = Appointment.BindToRecurringMaster(oAppt.Service, oAppt.Id);
                }
                catch (Exception ex)
                {

                }
            }
            else
            {

                recurringMaster = oAppt;



            }
            var deleteItem = recurringMaster.DeletedOccurrences;
            var editItem = recurringMaster.ModifiedOccurrences;
            if (editItem != null)
            {
                foreach (var item in editItem)
                {
                    try
                    {
                        var cccc = Appointment.Bind(recurringMaster.Service, item.ItemId, new PropertySet() { AppointmentSchema.Organizer, AppointmentSchema.ICalUid, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.OriginalStart });

                        var query = new ExchangeQuery(cccc.ICalUid, cccc.Organizer.Address, cccc.OriginalStart, cccc.End);
                        // double time = (query.start - DateTime.Now).TotalMinutes;
                        var email = ExChangeHelper.GetEmailListByMasterID(query);
                        // var userMaster = Appointment.BindToRecurringMaster(email.Service, email.Id, new PropertySet());
                        var userOccurrence = Appointment.Bind(email.Service, email.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Body, AppointmentSchema.RequiredAttendees, AppointmentSchema.Organizer, AppointmentSchema.Location, AppointmentSchema.ICalUid));
                        var entity = getEmailEntity(userOccurrence);
                        //   entity.itemId = item.ItemId.UniqueId;
                        //已修改的单次事件，在母版页修改时。保持原样，根据IcalUid更新未修改的子会议，根据已修改的会议id事件修改具体会议，不通过itemid进行修改。
                        Task<bool> a = dal.UpdateOccurrence(entity, 0, out string s);

                        Task<bool> b = dal.InsertZhouQiTemp(entity, out s);
                    }
                    catch (Exception)
                    {

                        continue;
                    }

                }
            }
            if (deleteItem != null)
            {
                foreach (var item in deleteItem)
                {
                    var aa = new EmailEntity();
                    aa.Start = item.OriginalStart;
                    aa.ID = oAppt.ICalUid;
                    dal.DeleteOccurrence(aa, 1, out string s);
                }

            }

            List<ZhouqiEntity> list = GetZhouqiItemList(recurringMaster);
            foreach (var item in list)
            {
                dal.UpdateOccurrence(item.EmailEntity, 0, out string s);
                Task<bool> b = dal.InsertZhouQiTemp(item.EmailEntity, out s);
            }


        }
        private List<ZhouqiEntity> getWeekly(EmailEntity meet, Appointment master, Recurrence.WeeklyPattern day, PropertySet properties)
        {
            int SourceType = 3;
            var list = new List<ZhouqiEntity>();
            var type = day.DaysOfTheWeek.ToString();
            if (day.NumberOfOccurrences is int)
            {
                for (int i = 1; i <= day.NumberOfOccurrences; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 6;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        continue;
                    }
                }
            }
            else
            {
                var starttime = day.StartDate; var endtime = day.EndDate;
                //  var count=endtime-day
                int itemsort = 1;
                for (int i = 1; starttime <= endtime; i++)
                {
                    try
                    {
                        if (type.Contains(starttime.DayOfWeek.ToString()))
                        {
                            var children = Appointment.BindToOccurrence(master.Service, master.Id, itemsort);
                            var ccccc = getEmailEntity(children);
                            ccccc.CycleMeetType = 6;
                            ccccc.SourceType = SourceType;
                            ccccc.sort = itemsort;
                            list.Add(new ZhouqiEntity()
                            {
                                IsDelete = false,
                                EmailEntity = ccccc,
                            });
                            itemsort++;
                        }
                        starttime = starttime.AddDays(1);
                        //  Console.WriteLine($"名称：{ccccc.Start}第{i}个元素,时间：{ccccc.Start}-{ccccc.End}");
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = itemsort
                            }
                        });
                        itemsort++;
                        starttime = starttime.AddDays(day.Interval);
                        continue;
                    }
                }
            }
            return list;
        }

        private List<ZhouqiEntity> getYearly(EmailEntity meet, Appointment master, Recurrence.YearlyPattern day, PropertySet properties)
        {
            int SourceType = 3;
            var list = new List<ZhouqiEntity>();

            if (day.NumberOfOccurrences is int)
            {
                for (int i = 1; i <= day.NumberOfOccurrences; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 8;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        continue;
                    }
                }
            }
            else
            {
                var starttime = day.StartDate; var endtime = day.EndDate;
                for (int i = 1; starttime <= endtime; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 8;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                        starttime = starttime.AddMonths(1);
                        //  Console.WriteLine($"名称：{ccccc.Start}第{i}个元素,时间：{ccccc.Start}-{ccccc.End}");
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        starttime = starttime.AddMonths(1);
                        continue;
                    }
                }
            }
            return list;
        }

        private List<ZhouqiEntity> getMonthly(EmailEntity meet, Appointment master, Recurrence.MonthlyPattern day, PropertySet properties)
        {
            int SourceType = 3;
            var list = new List<ZhouqiEntity>();
            if (day.NumberOfOccurrences is int)
            {
                for (int i = 1; i <= day.NumberOfOccurrences; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 7;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        continue;
                    }
                }
            }
            else
            {
                var starttime = day.StartDate; var endtime = day.EndDate;
                for (int i = 1; starttime <= endtime; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 7;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                        starttime = starttime.AddMonths(day.Interval);
                        //  Console.WriteLine($"名称：{ccccc.Start}第{i}个元素,时间：{ccccc.Start}-{ccccc.End}");
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        starttime = starttime.AddDays(day.Interval);
                        continue;
                    }
                }
            }
            return list;
        }

        private System.Threading.Tasks.Task<List<ZhouqiEntity>> getDaily(EmailEntity meet, Appointment master, Recurrence.DailyPattern day, PropertySet properties)
        {
            int SourceType = 3;
            var list = new List<ZhouqiEntity>();
            //  meet.CycleMeetType = 5;
            // meet.sort = 1;
            if (day.NumberOfOccurrences is int)
            {
                for (int i = 1; i <= day.NumberOfOccurrences; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 5;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                        //  Console.WriteLine($"ID:{ccccc.itemId},ICalUid:{ccccc.ID}名称：{ccccc.Start}第{i}个元素,时间：{ccccc.Start}-{ccccc.End}");
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        continue;
                    }
                }
            }
            else
            {
                var starttime = day.StartDate; var endtime = day.EndDate;
                for (int i = 1; starttime <= endtime; i++)
                {
                    try
                    {
                        var children = Appointment.BindToOccurrence(master.Service, master.Id, i, properties);
                        var ccccc = ExChangeHelper.GetEmailEntity(children);
                        ccccc.sort = i;
                        ccccc.CycleMeetType = 5;
                        ccccc.SourceType = SourceType;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = false,
                            EmailEntity = ccccc,
                        });
                        starttime = starttime.AddDays(day.Interval);
                        //  Console.WriteLine($"名称：{ccccc.Start}第{i}个元素,时间：{ccccc.Start}-{ccccc.End}");
                    }
                    catch (Exception e)
                    {
                        var c = e.Message;
                        list.Add(new ZhouqiEntity()
                        {
                            IsDelete = true,
                            EmailEntity = new EmailEntity()
                            {
                                sort = i
                            }
                        });
                        starttime = starttime.AddDays(day.Interval);
                        continue;
                    }
                }
            }
            return System.Threading.Tasks.Task.FromResult(list);
        }
        public static D Mapper<D, S>(S s)
        {
            D d = Activator.CreateInstance<D>(); //构造新实例
            try
            {
                var Types = s.GetType();//获得类型  
                var Typed = typeof(D);
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
                {
                    foreach (PropertyInfo dp in Typed.GetProperties())
                    {
                        if (dp.Name == sp.Name && dp.PropertyType == sp.PropertyType && dp.Name != "Error" && dp.Name != "Item")//判断属性名是否相同  
                        {
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;
        }

        //public bool Cannel(Appointment query)
        //{
        //    //var email = ExChangeHelper.GetEmailListByItemID(query);
        //    var (result, id) = dal.Cannel(query.ICalUid).Result;
        //    if (result)
        //    {
        //        var wx = new WeChatHelper();

        //        if (query.AppointmentType is AppointmentType.Single)
        //        {
        //            wx.SendChnnelMsg(id, false);
        //        }
        //        else
        //        {
        //            wx.SendChnnelMsg(id, true);
        //        }


        //    }
        //    return result;
        //}
      
        private EmailEntity getEmailEntity(Appointment email, string userAddress = "")
        {

            EmailEntity meet = new EmailEntity();
            meet.Start = email.Start;
            meet.End = email.End;
            meet.Body = "";
            meet.Subject = email.Subject;
            meet.Organizer = email.Organizer == null ? userAddress : email.Organizer.Address;
            meet.Location = email.Location;
            meet.AttendeesList = email.RequiredAttendees.Select(i => new Attendeee(i.Address, i.Name)).ToList();
            meet.ID = email.ICalUid;
            meet.itemId = email.Id.UniqueId;
            //会议状态
            int state = 0;
            //会议时长
            var CRoomIDs = new StringBuilder();
            string[] CRoomNames = meet.Location.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            string CroomName = "";
            for (int i = 0; i < CRoomNames.Length; i++)
            {
                CroomName = CRoomNames[i];
                if (CroomName.Contains("天一阁"))
                {
                    CRoomIDs.Append(dal.GetRoomrIDByName("天一阁")).Append(",");
                }
                else
                {
                    if (CroomName.Contains("（"))
                    {
                        CRoomIDs.Append(dal.GetRoomrIDByName(CroomName.Split('（')[0])).Append(",");
                    }
                    else
                    {
                        CRoomIDs.Append(dal.GetRoomrIDByName(CroomName)).Append(",");
                    }

                }

            }
            meet.CRoomIDs = CRoomIDs.ToString();
            //内部参会人ID  以,隔开
            var ParticipantIDs = new StringBuilder();
            try
            {
                var min = meet.End - meet.Start;
                meet.timelength = Convert.ToInt32(min.TotalMinutes.ToString());
            }
            catch (Exception)
            {
                meet.timelength = 0;
            }

            meet.CycleMeetGuid = Guid.NewGuid().ToString();
            //已结束
            if (meet.Start < DateTime.Now && meet.End < DateTime.Now)
            {
                state = 3;
            }
            //已预定
            else if (meet.Start > DateTime.Now && meet.End > DateTime.Now)
            {
                state = 1;
            }
            //进行中
            else if (meet.Start <= DateTime.Now && meet.End >= DateTime.Now)
            {
                state = 2;
            }
            meet.CreateID = dal.GetUserID(meet.Organizer);

            meet.state = state;
            if (meet.AttendeesList.Count > 0)
            {
                foreach (var Attendee in meet.AttendeesList)
                {
                    ParticipantIDs.Append(dal.GetUserID(Attendee.Address)).Append(",");
                }
                meet.ParticipantIDs = ParticipantIDs.ToString();
            }

            return meet;
        }


        public string Operator { get; private set; }
        public string OperaIP { get; private set; }

        //public void NotAccept(Appointment oAppt)
        //{
        //    var aa = new WeChatHelper();
        //    var (result, id) = dal.Cannel(oAppt.ICalUid).Result;

        //    aa.senNotAcceptMsg(oAppt.Organizer.Address, oAppt.Subject, oAppt.Location, oAppt.Start, oAppt.End);
        //}

        private object UpdateChanel(string calUid)
        {
            throw new NotImplementedException();
        }

        public string GetOccurrenceIDByindex(Appointment Master, int index)
        {

            Appointment occurrence = Appointment.BindToOccurrence(Master.Service,
                                                               Master.Id,
                                                               index, // Index of first item is 1, not 0.
                                                               new PropertySet(BasePropertySet.IdOnly));
            return occurrence.Id.UniqueId;
        }
    }
}
